package org.ww.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.ww.servicebase.exceptionhandler.GuliException;
import org.ww.vod.service.VodService;
import org.ww.vod.utils.ConstantsVodUtil;
import org.ww.vod.utils.InitVodClient;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {
    /**
     * 上传视频到阿里云
     * @param file
     * @return
     */
    @Override
    public String uploadVod(MultipartFile file) {
        try{
            String accessKeyId=ConstantsVodUtil.ACCESS_KEY_ID;
            String accessKeySecret=ConstantsVodUtil.ACCESS_KEY_SECRET;
            //文件路径
            String fileName=file.getOriginalFilename();
            //在阿里云上显示的视频名称
            String title=fileName.substring(0,fileName.lastIndexOf("."));

            InputStream inputStream=file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (response.isSuccess()) {
               return response.getVideoId();
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
               return response.getVideoId();
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 批量删除视频
     * @param videoIds
     */
    @Override
    public void deleteBatch(List videoIds) {
        //根据id删除阿里云视频
        try{
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantsVodUtil.ACCESS_KEY_ID, ConstantsVodUtil.ACCESS_KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request=new DeleteVideoRequest();
            //将list集合编程字符串形式
            String data = StringUtils.join(videoIds, ",");
            //向request中设置视频id
            request.setVideoIds(data);
            //调用初始化对象的方法实现删除
            client.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败！");
        }
    }
}
